package com.itheima.work;

import java.util.concurrent.CountDownLatch;

/**
 * @auther Macrydy
 * @date 2020/7/9 19:11
 * 请使用CountDownLatch编写一个程序，实现以下效果：
 *
 * ​       3人参加百米赛跑.裁判在三人都到达终点后宣布比赛结果.
 *
 * ​    使用面向对象思想:运动员是一个线程类.裁判是一个线程类.
 */
public class Test4 {
    public static void main(String[] args) {

        CountDownLatch cdl = new CountDownLatch(3);
        //裁判
        Referee referee = new Referee(cdl);
        referee.start();

        //运动员
        Runner runner = new Runner(cdl);
        Thread t1 = new Thread(new Runner(cdl),"小明");
        Thread t2 = new Thread(new Runner(cdl),"小王");
        Thread t3 = new Thread(new Runner(cdl),"小红");
        t1.start();
        t2.start();
        t3.start();

    }
}
class Runner implements Runnable{
    private CountDownLatch countDownLatch;

    public Runner(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        synchronized (Referee.class) {
            System.out.println(Thread.currentThread().getName()+"跑到了终点");
//            System.out.println(countDownLatch.getCount());
            countDownLatch.countDown();
        }
    }
}


class Referee extends Thread {
    private CountDownLatch countDownLatch;

    public Referee(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        System.out.println("比赛开始");
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("比赛结束");
    }
}